<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use language\Languagemsg;
use think\Db;

class Ali extends Base
{
    protected $config = array(
        'appId' => '2021002116679854',
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3HNl8R21vp6BcIRuRPlLpffGLXryszfWOhaErwXV866V5MmBjmSHmV4NeBscjJGo4FdST84P3SoayFBSQwFIxixAAkwOO7Ub+Uev4BHXRv1SpT+zMnyA9Koo7gCl2PVGtjUCKr6r+1zEEgYeQAKApks0TZzW8NBkcc7l1jKP1cJR4SYswXYw0jVB7OjbFQ+M2pyAuHHLKTpht8i63xNKjOfgliMNQ2k+SpBmj9aBsjioF/bhs4HWhDFbz1fufAqQ8/qf5/3+Sj1AOdz3qLdm+T9SiyU8eQH7h0etK+d4CPsLbSokiIiUBGBzwForhqzTUdx8x6KcrbgdZcbZ09LRnQIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArPGVCPqYOjGxXpatXtMbTHkRul9fVgXG9ybu7Xs6zgoA7g7E7fFW0cNbSBJmpkrNoOelDkzH/QL0971DsQrbUjY1Cw7KFDhMOyu8yPEOsdSh/Pzk1Ip7fnszRKhpMWxgrQYR8/EguOoZLWmioQCtqMs3OZRIB18Tgm1n27MvwQRk0L1tVTEtVcWEEYYfnBOcmZFtGb4Y+zKGKSauoX4pu+gALmP9bSrHpDsBI1zlh4EjKFuum9CskEbFeJVSDhaEDjawoJlcuGj5BOzF7DhCny4e1DehMd0ZifZPaYRJqlDgDA2KDowniBaxXDE75stCMSRXfLJOCht5V1vbub8b1wIDAQAB",
        'private_key' => 'MIIEpAIBAAKCAQEArPGVCPqYOjGxXpatXtMbTHkRul9fVgXG9ybu7Xs6zgoA7g7E7fFW0cNbSBJmpkrNoOelDkzH/QL0971DsQrbUjY1Cw7KFDhMOyu8yPEOsdSh/Pzk1Ip7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iF2SlLYVIjsP2e8UVl0qme9bU7yQKBgQCaLE4NDqhzX4KnF2N5BRGU83XZ1vF3L8ynkSp0IH2rMMfibvVFSKdnbHEQ57beycAlC5TXQmZ4qg0trjuQxtJ5ywzu6ACMIVF0Mdra09b2rrvlnDk5bZnw157VJaXuvHyFJo+2HMpWeKDTv6QYi5fTw4aw0G5y9Jlte2hNjwtzowKBgQCRq6ipAsdSrZjj6PEbnsynVCCTbj8DbrSSmzRdYbZydOhljoxDk9k3nVdAbyjtPgHxUTFnl41e2x+/UTHHeIsYLyQwYx+m3me9WGIY4DwtCJTnIU/raJBASeVblFP1Gz0wlXXs/IKvEtmYFL5tuxQf3agjzW3zy7X4pabBmaK/lQ=='
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->msg_language = new Languagemsg();
        $this->language = input('language') ? input('language') : 0; // 0 汉语  1 英语  2 日语
        $useridddd = input('user_id');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($useridddd,$time,$value,$reqKey);
        if($auth == 112){
//            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            echo json_encode(['status'=>301,'msg'=>$this->msg_language->otherLogin[$this->language]]);
            exit;
        }elseif($auth == 2111){
//            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            echo json_encode(['status' => 302, 'msg' => $this->msg_language->frost[$this->language]]);
            exit;
        }
    }
    
    /**
     * @param $no   订单号
     * @param $money   金额
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);

        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = $this->config['appId'];
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://yue.xuanwumobile.com/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msgsss'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msgsss'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }
    
    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    
    /**
     * 更新订单
     * @return
     * order_id    订单ID
     */
    public function alipay()
    {
        $order_id = input('order_id');
        $res = Db::table('up_goods_order')
            ->where('order_id', $order_id)
            ->update(['order_pay_type' => 2, 'order_updatetime' => date('Y-m-d H:i:s')]);
        if($res){
            $this->body = '订单支付';
            $this->subject = '订单支付';
            $order = Db::table('up_goods_order')
                ->where('order_id', $order_id)
                ->field('order_number, order_pay_price')
                ->find();
//            $this->total_amount = $order['order_pay_price'];
        $this->total_amount = 0.01;
            $this->out_trade_no = $order['order_number'];
            $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
            return json_encode($respont);
        }else{
//            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
            return json(['status' => 0, 'msg' => $this->msg_language->systemErr[$this->language]]);
        }
    }
    
    /**
     * 打印回调内容
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }
    
    /**
     * 回调
     * @return string
     */
    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no']; //订单号
                $order = Db::table('up_goods_order')
                    ->where('order_number', $num)
                    ->field('order_id, order_num, order_goods_id, order_buy_user_id, order_sail_user_id, 
                    order_type, order_yue_id, order_spec_id, order_status')
                    ->find();
                
                if($order['order_status'] == 1){
                    Db::startTrans();
                    try{
                        // 修改订单状态
                        Db::table('up_goods_order')
                            ->where('order_id', $order['order_id'])
                            ->update([
                                'order_status' => 2,
                                'order_pay_time' => date('Y-m-d H:i:s'),
                                'order_pay_date' => date('Y-m-d')
                            ]);
                        
                        // 约稿订单
                        if($order['order_type'] == 4){
                            Db::table('up_yue')->where('yue_id', $order['order_yue_id'])->setField('yue_status', 2);
                        }
                        
                        // 除了押金订单，其他的需要给画师发个信息
                        if($order['order_type'] != 5){
                            $notice = [
                                'notice_title' => '您有一个订单已付款',
                                'notice_content' => '您有一个订单已付款',
                                'notice_user' => ',' . $order['order_sail_user_id'] . ',',
                                'notice_type' => 5,
                                'notice_order_id' => $order['order_id'],
                                'notice_read_user' => ',0,',
                                'notice_del_user' => ',0,',
                                'notice_time' => date('Y-m-d H:i:s')
                            ];
                            Db::table('up_notice')->insert($notice);
                        }
                        
                        Db::commit();
                        return 'success';
                    }catch(\Exception $e){
                        Db::rollback();//回滚
                        return 'error';
                    }
                }else{
                    return 'success';
                }
                
            }
        }
    }


    /**
     *支付宝的原路退款接口(商户处理用户的订单)
     */
    public function refund(){
        $payInfo = array();
        $payInfo['number'] = '201905311701374074';
        $payInfo['money'] = 12;
        //仨参数：money,number
        import('alipay.aop.AopClient',EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeRefundRequest',EXTEND_PATH);
        $aop = new \AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2019080566158002';
        $aop->rsaPrivateKey = $this->config['private_key'];
        $aop->alipayrsaPublicKey=$this->config['public_key']; //不应该用这个，用ali_public
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest;
        $refundAmount = $payInfo['money'];
        $request->setBizContent("{" .
            "\"out_trade_no\":\"".$payInfo['number']."\"," .
            "\"trade_no\":\"\"," .
            "\"refund_amount\":".$refundAmount."," .
            "\"refund_reason\":\"退款\"" .
            "  }");
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) && $resultCode == 10000){
//            return array('status' => 200, 'msg' => '操作成功');
            return array('status' => 200, 'msg' => $this->msg_language->doSuccess[$this->language]);
        }else{
//            return array('status' => 0, 'msg' => '调用接口失败');
            return array('status' => 0, 'msg' => $this->msg_language->apiErr[$this->language]);
        }
    }
}